package com.huangyi.adminservice.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.huangyi.adminapi.appuser.domain.dto.AppUserDTO;
import com.huangyi.adminapi.appuser.domain.dto.AppUserListReqDTO;
import com.huangyi.adminapi.appuser.domain.dto.UserEditReqDTO;
import com.huangyi.adminservice.user.controller.RabbitConfig;
import com.huangyi.adminservice.user.domain.entity.AppUser;
import com.huangyi.adminservice.user.mapper.AppUserMapper;
import com.huangyi.adminservice.user.service.IAppUserService;
import com.huangyi.commoncore.domain.dto.BasePageDTO;
import com.huangyi.commoncore.utils.AESUtil;
import com.huangyi.commoncore.utils.VerifyUtil;
import com.huangyi.commondomain.domain.ResultCode;
import com.huangyi.commondomain.exception.ServiceException;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;


/**
 * C端用户服务层实现类
 */
@Component
@Slf4j
@RefreshScope
public class AppUserServiceImpl implements IAppUserService {

    /**
     * 默认头像
     */
    @Value("${appuser.info.defaultAvatar}")
    private String defaultAvatar;
    /**
     * C端用户接口服务类
     */
    @Autowired
    private AppUserMapper appUserMapper;

    /**
     * rabbitMq工具类对象
     */
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 根据微信注册用户
     * @param openId 用户微信ID
     * @return C端用户DTO
     */
    @Override
    public AppUserDTO registerByOpenId(String openId) {
        AppUserDTO appUserDTO = new AppUserDTO();
        if(StringUtils.isEmpty(openId)){
            throw new ServiceException("微信ID不能为空" ,ResultCode.INVALID_REGION.getCode());
        }
        AppUser appUser = new AppUser();
        appUser.setOpenId(openId);
        appUser.setNickName("用戶" + (int)(Math.random()*9000)+1000);
        appUser.setAvatar(defaultAvatar);
        appUserMapper.insert(appUser);
        BeanUtils.copyProperties(appUser,appUserDTO);
        appUserDTO.setUserId(appUser.getId());
        return appUserDTO;
    }


    /**
     * 根据openId查询用户信息
     * @param openId 用户微信ID
     * @return C端用户DTO
     */
    @Override
    public AppUserDTO findByOpenId(String openId) {
        if(StringUtils.isEmpty(openId)){
            return null;
        }
        AppUser appUser = appUserMapper.selectByOpenId(openId);
        if(appUser == null){
            throw new ServiceException("用户openId不存在" ,ResultCode.INVALID_REGION.getCode()); //
        }
        AppUserDTO appUserDTO = new AppUserDTO();
        BeanUtils.copyProperties(appUser,appUserDTO);
        appUserDTO.setPhoneNumber(AESUtil.encryptHex(appUser.getPhoneNumber()));
        appUserDTO.setUserId(appUser.getId());
        return appUserDTO;
    }

    /**
     * 编辑C端用户
     * @param userEditReqDTO C端用户DTO
     * @return void
     */
    @Override
    public void edit(UserEditReqDTO userEditReqDTO) {
        AppUser appUser = appUserMapper.selectById(userEditReqDTO.getUserId());
        if(appUser == null){
            throw new ServiceException("用户不存在" ,ResultCode.INVALID_REGION.getCode());
        }
        appUser.setNickName(userEditReqDTO.getNickName());
        appUser.setAvatar(userEditReqDTO.getAvtar());
        appUserMapper.updateById(appUser);

        AppUserDTO appUserDTO = new AppUserDTO();
        BeanUtils.copyProperties(appUser,appUserDTO);
        appUserDTO.setUserId(appUser.getId());
        try {
            rabbitTemplate.convertAndSend(RabbitConfig.EXCHANGE_NAME, "", appUserDTO);
        }catch (Exception e){
            log.error("发送消息失败" + e.getMessage());
        }
    }


    /**
     * 查询C端用户
     * @param appUserListReqDTO 查询C端用户DTO
     * @return C端用户分页结果
     */
    @Override
    public BasePageDTO<AppUserDTO> getUserList(AppUserListReqDTO appUserListReqDTO) {
       // 手机明文转加密
        appUserListReqDTO.setPhoneNumber(AESUtil.encryptHex(appUserListReqDTO.getPhoneNumber()));
        BasePageDTO<AppUserDTO> result = new BasePageDTO<>();
        // 查询对象总数
        Long total = appUserMapper.selectCount(appUserListReqDTO);
        if(total == 0){
            result.setTotals(0);
            result.setTotalPages(0);
            result.setList(new ArrayList<>());
            return result;
        }
        // 分页查询 设置信息
        List<AppUser> appUsers = appUserMapper.selectPage(appUserListReqDTO);
        List<AppUserDTO> appUserDTOS = new ArrayList<>();
        result.setList(appUserDTOS);
        result.setTotalPages(
                BasePageDTO.calculateTotalPages(total,appUserListReqDTO.getPageSize())
        );
        result.setTotals(total.intValue());
        // 超页判断
        if(CollectionUtils.isEmpty(appUsers)){
            result.setList(new ArrayList<>());
            return result;
        }

        // 转换实体类
        for (AppUser appUser : appUsers) {
            AppUserDTO appUserDTO = new AppUserDTO();
            BeanUtils.copyProperties(appUser,appUserDTO);
            appUserDTO.setUserId(appUser.getId());
            if(appUser.getPhoneNumber() != null){
                appUserDTO.setPhoneNumber(AESUtil.decryptHex(appUser.getPhoneNumber()));
            }
            appUser.setPhoneNumber(null);
            appUserDTOS.add(appUserDTO);
        }
        result.setList(appUserDTOS);
        return result;
    }


    /**
     * 根据用户ID获取用户信息
     * @param userId 用户ID
     * @return C端用户DTO
     */
    @Override
    public AppUserDTO findById(Long userId) {
        if(userId == null){
            return null;
        }
        AppUser appUser = appUserMapper.selectById(userId);
        if(appUser == null){
            return null;
        }
        AppUserDTO appUserDTO = new AppUserDTO();
        BeanUtils.copyProperties(appUser,appUserDTO);
        appUserDTO.setUserId(appUser.getId());
        appUserDTO.setPhoneNumber(AESUtil.decryptHex(appUser.getPhoneNumber()));
        return appUserDTO;
    }

    /**
     * 根据用户ID列表获取用户列表信息
     * @param userIds 用户ID列表
     * @return C端用户DTO列表
     */
    @Override
    public List<AppUserDTO> getUserList(List<Long> userIds) {
        List<AppUser> appUsers = appUserMapper.selectList(new LambdaQueryWrapper<AppUser>().in(AppUser::getId, userIds));
        if(CollectionUtils.isEmpty(appUsers)){
            return new ArrayList<>();
        }
        List<AppUserDTO> appUserDTOS = new ArrayList<>();
        for (AppUser appUser : appUsers) {
            AppUserDTO appUserDTO = new AppUserDTO();
            BeanUtils.copyProperties(appUser,appUserDTO);
            appUserDTO.setUserId(appUser.getId());
            appUserDTO.setPhoneNumber(AESUtil.decryptHex(appUser.getPhoneNumber()));
            appUserDTOS.add(appUserDTO);
        }
        return appUserDTOS;
    }


    /**
     * 根据手机号查询用户信息
     * @param phoneNumber 手机号
     * @return C端用户DTO
     */
    @Override
    public AppUserDTO findByPhone(String phoneNumber) {
        // 1 判断手机号是否为空
        if (StringUtils.isEmpty(phoneNumber)) {
            throw new ServiceException("手机号不能为空", ResultCode.INVALID_PARA.getCode());
        }
        // 2 判断手机号格式
        if(!VerifyUtil.checkPhone(phoneNumber)){
            throw new ServiceException("手机号格式错误" ,ResultCode.INVALID_REGION.getCode());
        }
        // 3 手机号转密文, 进 mysql 查询对象
        AppUser appUser = appUserMapper.selectByPhoneNumber(AESUtil.encryptHex(phoneNumber));
        if(appUser == null){
            return null;
        }
        AppUserDTO appUserDTO = new AppUserDTO();
        BeanUtils.copyProperties(appUser,appUserDTO);
        appUserDTO.setUserId(appUser.getId());
        appUserDTO.setPhoneNumber(AESUtil.decryptHex(appUser.getPhoneNumber()));

        return appUserDTO;
    }



    /**
     * 根据手机号注册用户
     * @param phoneNumber 手机号
     * @return C端用户DTO
     */
    @Override
    public AppUserDTO registerByPhone(String phoneNumber) {
        // 1 判断手机号是否为空
        if (StringUtils.isEmpty(phoneNumber)) {
            throw new ServiceException("手机号不能为空", ResultCode.INVALID_PARA.getCode());
        }
        // 2 检查手机号格式是否正确
        if(!VerifyUtil.checkPhone(phoneNumber)){
            throw new ServiceException("手机格式错误",ResultCode.INVALID_REGION.getCode());
        }


        // 3 插入对象
        Random random = new Random();
        AppUser appUser = new AppUser();
        appUser.setPhoneNumber(AESUtil.encryptHex(phoneNumber));
        appUser.setAvatar(defaultAvatar);
        appUser.setNickName("用户" + (int)(Math.random()*9000)+1000);
        appUserMapper.insert(appUser);

        // 4 构建返回对象
        AppUserDTO appUserDTO = new AppUserDTO();
        BeanUtils.copyProperties(appUser,appUserDTO);
        appUserDTO.setUserId(appUser.getId());

        return appUserDTO;
    }


}
